
package com.jf.cloud.service.sysmanager.remote.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.constant.MatchConstant;
import com.jf.cloud.service.sysmanager.dao.IPubgClubService;
import com.jf.cloud.service.sysmanager.dao.IPubgMatchMsgService;
import com.jf.cloud.service.sysmanager.dao.IPubgMatchService;
import com.jf.cloud.service.sysmanager.dao.IPubgMatchSettlementService;
import com.jf.cloud.service.sysmanager.dao.IPubgMsgLogService;
import com.jf.cloud.service.sysmanager.dao.IPubgOperateLogService;
import com.jf.cloud.service.sysmanager.dao.IPubgTeamService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserService;
import com.jf.cloud.service.sysmanager.entity.PubgClub;
import com.jf.cloud.service.sysmanager.entity.PubgMatch;
import com.jf.cloud.service.sysmanager.entity.PubgMatchSettlement;
import com.jf.cloud.service.sysmanager.entity.PubgTeam;
import com.jf.cloud.service.sysmanager.entity.PubgUser;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 俱乐部控制器
 * 
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/appClub")
public class AppPubgClubController extends BaseController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(AppPubgClubController.class);

	/**
	 * 俱乐部服务
	 */
	@Resource
	private IPubgClubService pubgClubService;
	
	@Resource
	private IPubgTeamService pubgTeamService;

	@Resource
	private IPubgUserService pubgUserService;
	
	@Resource
	private IPubgMatchService pubgMatchService;
	
	@Resource
	private TokenHandler tokenHandler;
	
	@Resource
	private IPubgOperateLogService pubgOperateLogService;
	
	@Resource
	private IPubgMsgLogService pubgMsgLogService;
	
	@Resource
	private IPubgMatchMsgService pubgMatchMsgService;
	
	@Resource
	private IPubgMatchSettlementService pubgMatchSettlementService;
	
	/**
	 * 获取俱乐部详情
	 * 
	 * @author 朱建文 创建时间：2018年4月2日 上午11:00:46
	 */
	@ResponseBody
	@RequestMapping("/clubDeatil")
	public Result<PubgClub> getMyClubDetail(String token, Long rowId, HttpServletRequest request){
		Result<PubgClub> result = new Result<PubgClub>();
		result.setCode(-1);
		result.setMessage("获取俱乐部详情失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
			    result.setCode(-2);
			    result.setMessage("请重新登陆！");
			    return result;
			}
            Map<String,String> columns = new HashMap<String,String>();
            columns.put("ROW_ID", "rowId");
            columns.put("CLUB_NO", "clubNo");
            columns.put("CLUB_NAME", "clubName");
            columns.put("MINISTER_ID", "ministerId");
            columns.put("MINISTER_NAME", "ministerName");
            columns.put("INVITE_CODE", "inviteCode");
            columns.put("CLUB_INTRO", "clubIntro");

			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", "," + userId + ",");
			PubgClub pubgClub = this.pubgClubService.find(columns, query);
			result.setData(pubgClub);
			result.setCode(0);
			result.setMessage("获取俱乐部详情成功！");
		} catch (Exception e) {
			log.error("获取俱乐部详情出错！", e);
		}
		return result;
	}
	
	/**
	 * 更新战队余额
	 * 
	 * @author 朱建文 创建时间：2018年4月4日 下午2:17:28
	 */
	@ResponseBody
	@RequestMapping("/updateTeamBalance")
	public Result<String> updateTeamBalance(Long tramId, Double optMoney, HttpServletRequest request, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("更新战队余额失败！");
		
		try {
			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 验证 操作方式   1 加款   2 减款
			int optType = getParamValueInteger(request, "optType", -1);
			if (optType < 0) {
				result.setMessage("操作方式为空！");
				return result;
			}
			if (optMoney == null || optMoney < 0) {
				result.setMessage("操作金额必须大于0！");
				return result;
			}
			
			// 战队是否存在
			PubgTeam pubgTeam = this.pubgTeamService.findByPK(tramId);
			if (pubgTeam == null) {
				result.setMessage("战队不存在！");
				return result;
			}
			
			// 操作者是否是部长
			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", "," + optId + ",");
			PubgClub pubgClub = this.pubgClubService.find(query);
			if (pubgClub == null) {
				result.setMessage("您当前还不是部长！");
				return result;
			}
			
			// 该战队是否属于该俱乐部
			if (!pubgTeam.getClubId().equals(pubgClub.getRowId())) {
				result.setMessage("您无权操作当前战队！");
				return result;
			}
			
			// 加，需要验证俱乐部下的余额
			if (1 == optType && optMoney > pubgClub.getClubBalance()) {
				result.setMessage("操作金额不能大于俱乐部的余额！");
				return result;
			}
			
			// 如果是减，需要验证当前战队余额
			if (2 == optType && optMoney > pubgTeam.getTeamBalance()) {
				result.setMessage("操作金额不能大于战队的余额！");
				return result;
			}
			
			// 更新战队余额、充值总额
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(optId));
			pubgTeam.setOptId(pubgUser.getRowId());
			pubgTeam.setOptAccount(pubgUser.getUserAccount());
			this.pubgClubService.updateTeamBalance(pubgClub, pubgTeam, optType, optMoney);
			
			// 插入操作记录
			String relationDes = "对战队【" + pubgTeam.getTeamName() + "】加鸡蛋" + optMoney;
			if (2 == optType) {
				relationDes = "对战队【" + pubgTeam.getTeamName() + "】减鸡蛋：" + optMoney;
			}
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, relationDes);
			result.setCode(0);
			result.setMessage("更新战队余额成功！");
		} catch (Exception e) {
			log.error("更新战队余额出错！", e);
		}
		return result;
	}
	
	/**
	 * 更新赛事状态
	 * 
	 * @author 朱建文 创建时间：2018年4月8日 下午2:57:10
	 */
	@ResponseBody
	@RequestMapping("/updateMatchState")
	public Result<String> updateMatchState(Long matchId, String matchState, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("更新赛事状态失败！");
		try {
		
			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 验证操作者身份
			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", "," + optId + ",");
			PubgClub pubgClub = this.pubgClubService.find(query);
			if (pubgClub == null) {
				result.setMessage("您当前还不是部长！");
				return result;
			}
			
			// 验证赛事是否存在
			PubgMatch pubgMatch = this.pubgMatchService.findByPK(matchId);
			if (pubgMatch == null) {
				result.setMessage("赛事不存在！");
				return result;
			}
			
			// 验证操作者与赛事的关系
			if (!pubgMatch.getClubId().equals(pubgClub.getRowId())) {
				result.setMessage("您无权操作该赛事！");
				return result;
			}
			
			// 验证赛事状态是否合法
			if (!MatchConstant.isExist(matchState)) {
				result.setMessage("状态有误！");
				return result;
			}
			
			// 更新赛事状态
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(optId));
			this.pubgClubService.updateMatchState(pubgMatch, matchState, pubgUser);
			
			// 插入操作记录
			String relationDes = "更新赛事【" + pubgMatch.getMatchName() + "】状态为:" + matchState;
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, relationDes);

			// 给队员记录消息
			if ((MatchConstant.MATCH_STATE_80.getId() + "").equals(matchState)) {
				pubgMsgLogService.insertPbugMsgLog(pubgUser.getRowId(), 10L, "赛事取消通知", "赛事调整，详情联系队长！");
			}
			
			// 插入队员消息
			if ((MatchConstant.MATCH_STATE_40.getId() + "").equals(matchState)) {
				String content = "您报名的【" + pubgMatch.getMatchName() + "】比赛现在开始入场，";
				content += "房间名：" + pubgMatch.getRoomName() + "，密码：" + pubgMatch.getRoomPwd() + "，您有5分钟入场时间。";
				pubgMsgLogService.insertPbugMsgLog(matchId, "赛事准备通知", content);
			}
			
			result.setCode(0);
			result.setMessage("更新赛事状态成功！");
		} catch (Exception e) {
			log.error("更新赛事状态出错！", e);
		}
		return result;
	}
	
	/**
	 * 确认战绩
	 * 
	 * @author 朱建文 创建时间：2018年4月8日 下午7:33:34
	 */
	@ResponseBody
	@RequestMapping("/confirmMatchResult")
	public Result<String> confirmMatchResult(Long matchId, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("更新赛事状态失败！");
		try {

			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 验证操作者身份
			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", "," + optId + ",");
			PubgClub pubgClub = this.pubgClubService.find(query);
			if (pubgClub == null) {
				result.setMessage("您当前还不是部长！");
				return result;
			}
			
			// 验证赛事是否存在
			PubgMatch pubgMatch = this.pubgMatchService.findByPK(matchId);
			if (pubgMatch == null) {
				result.setMessage("赛事不存在！");
				return result;
			}
			
			// 验证操作者与赛事的关系
			if (!pubgMatch.getClubId().equals(pubgClub.getRowId())) {
				result.setMessage("您无权操作该赛事！");
				return result;
			}
			
			// 赛事的状态
			if (MatchConstant.MATCH_STATE_70.getId().toString().equals(pubgMatch.getMatchState())) {
				result.setCode(0);
				result.setMessage("赛事已结束！");
				return result;
			}
			
			// 更新赛事状态、计算利润分配等
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(optId));
			this.pubgClubService.confirmMatchResult(pubgMatch, pubgClub, pubgUser);
			result.setCode(0);
			result.setMessage("确认战绩成功！");
			
			// 插入操作记录
			String relationDes = pubgUser.getUserAccount() + "赛事【" + pubgMatch.getMatchName() + "】确认战绩";
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, relationDes);

			// 插入赛事消息, 给获奖队员发送消息
			query = new Query();
			query.put("MATCH_ID", matchId);
			query.put("_NOT_NULL$USER_ID");
			List<PubgMatchSettlement> dataList = pubgMatchSettlementService.findList(query);
			String temp = "恭喜您获得【" + pubgMatch.getMatchName() + "】比赛", content = "";
			for (PubgMatchSettlement settlement : dataList) {
				content = temp + "第" + settlement.getObtainRank() + "名，继续加油哦！";
				pubgMsgLogService.insertPbugMsgLog(settlement.getUserId(), 10L, "赛事吃鸡通知", content);
			}
		} catch (Exception e) {
			log.error("确认战绩出错！", e);
		} 
		return result;
	}
}
